package com.kgc.resolver;

import com.alibaba.fastjson.JSON;
import com.kgc.bean.User;
import com.kgc.config.annotation.RequestUser;

import com.kgc.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @Classname RequestUserResolver
 * @Description 自定义用户信息解析器
 * @Date 2021/6/17 16:54
 * @Created by 17402
 */
public class RequestUserResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //强制指定：方法的形参必须是加了自定义参数注解RequestUser,且解析目标实体类型必须为User
        return methodParameter.hasParameterAnnotation(RequestUser.class)&&methodParameter.getParameterType().isAssignableFrom(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {

        //从redis获取user信息
        Object userObj=redisUtils.get(nativeWebRequest.getHeader("token"));
        //解析用户对象
        if(null==userObj){
            return null;
        }
        return JSON.parseObject(userObj.toString(), User.class);

    }
}
